<template>
  <div class="navigate-container h-100">
    <el-card class="h-100">
      <div class="title m-5"><span>{{ $t('NAVIGATE_TO_FAULT_POINT') }}</span></div>
      <div class="start m-5">
        <span>{{ $t('START_POINT') }}：</span>
        <el-autocomplete
          v-model="filterText"
          class="search"
          popper-class="gaode-search"
          style="width: 300px"
          :placeholder="$t('ENTER_LOCATION_SEARCH')"
          clearable
          :fetch-suggestions="querySearchAsync"
          :hide-loading="true"
          @select="handleSelect"
          @change="change"
        >
          <template slot-scope="{ item }">
            <div class="name">{{ item.name }}</div>
            <span class="addr"> {{ item.district || '--' }} | {{ item.address || '--' }}</span>
          </template>
          <el-button slot="append" icon="el-icon-search" @click="query" />
        </el-autocomplete>
      </div>
      <div class="end m-5">
        <span>{{ $t('END_POINT') }}（{{ $t('FAULT_LOCATION_POINT') }}）：{{ endPointName }}</span>
      </div>
      <div id="navigate-panel" class="mt-10" />
    </el-card>
  </div>
</template>
<script>
  export default {
    props: {
      faultLocation: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        filterText: '',
        startPointLngLat: [],
        endPointName: ''
      }
    },
    computed: {
      autoComplete() {
        return new AMap.Autocomplete({
          datatype: 'poi'
        })
      },
      map() {
        return this.$parent.$parent.map
      },
      navigateDriving() {
        return new AMap.Driving({
          map: this.map,
          panel: 'navigate-panel'
        })
      },
      geocoder() {
        return new AMap.Geocoder({ city: '全国' })
      }
    },
    watch: {
      faultLocation: {
        handler(newVal) {
          console.log('faultLocation', newVal)

          this.reset()
          if (newVal.length) {
            this.geocoder.getAddress(newVal, (status, result) => {
              console.log('faultLocation', result)

              if (status === 'complete' && result.regeocode) {
                this.endPointName = result.regeocode.formattedAddress
              }
            })
          }
        }
      }
    },
    methods: {
      querySearchAsync(queryString, cb) {
        if (!queryString) return
        // 根据输入关键字返回匹配结果
        this.autoComplete.search(queryString, (status, result) => {
          console.log('搜索结果', status, result)
          if (status === 'error') {
            this.$message.error(this.$t(result))
            return
          }
          if (status !== 'complete' || !result || result.info !== 'OK') {
            this.$message.error(this.$t('NO_SEARCH_RESULT'))
            return
          }
          const list = result.tips || []
          cb(list.filter(i => i.location))
        })
      },
      handleSelect(item) {
        console.log(item)
        this.filterText = item.name
        this.startPointLngLat = item.location
      // 根据选中的位置，定位到具体位置
      },
      change(val) {
        if (!val) {
          this.navigateDriving.clear()
        }
      },
      query() {
        if (!this.endPointName || !this.faultLocation.length) {
          this.$message.error(this.$t('CANNOT_NAVIGATE_TO_FAULT_POINT'))
          return
        }
        this.navigateDriving.search(
          this.startPointLngLat,
          new AMap.LngLat(this.faultLocation[0], this.faultLocation[1]),
          (status, result) => {
            if (status === 'complete') {
              const routeData = result.routes[0]
              let path = []
              routeData && routeData.steps.forEach(i => {
                path = [...path, ...i.path]
              })
              this.$emit('setNavPath', path.map(i => [i.lng, i.lat]))
            } else {
              console.log('获取驾车数据失败：' + result)
            }
          }
        )
      },
      reset() {
        this.navigateDriving && this.navigateDriving.clear()
        this.endPointName = ''
        this.filterText = ''
        this.startPointLngLat = null
      }
    }
  }
</script>
<style lang="scss">
@import '@/assets/css/mixin.module.scss';
.navigate-container {
  top: 0;
  right: 0;
  z-index: 6;
  width: 350px;
  @include themeify {
    background: themed('topoBg');
  }
  .el-card__body {
    height: 100%;
    display: flex;
    flex-direction: column;
    .title {
      text-align: center;
      @include themeify {
        color: themed('gisTitleColor');
      }
    }
    .start {
      display: flex;
      flex-wrap: nowrap;
      align-items: center;
      .search {
        flex: 1;
      }
    }
  }
  #navigate-panel {
    flex: 1;
    overflow-y: auto;
  }
}
</style>
